import router from './router'
import store from './store'
import {Message} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// import {getToken} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import {asyncRouter} from '@/router'

NProgress.configure({showSpinner: false}) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  // const hasToken = getToken()

  if (store.getters.token) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next('/')
      NProgress.done()
    } else {
      // 是否获取过资料
      if (!store.getters.userId) {
        // get user info
        const {roles} = await store.dispatch('user/getUserInfo')
        // console.log(roles.menus) // 数组 不确定
        // console.log(asyncRouter) // 数组 8个

        // 两个数组筛选---数据的操作
        // filterRouter筛选后的路由 每个人看到的路由不同
        const filterRouter = asyncRouter.filter(item => {
          // return true/false
          return roles.menus.includes(item.name)
        })
        // 存储过滤之后的路由
        store.commit('user/setRoutes', filterRouter)
        // 404 要放在所有路由的最后
        router.addRoutes([...filterRouter, {path: '*', redirect: '/404', hidden: true}]) // 添加动态路由信息到路由表
        // router添加动态路由之后需要转发一下
        next(to.path) // 目的是让路由拥有信息  router的已经缺陷
      } else {
        next()
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
